<template>
  <section class="content" id="content">
    <!-- 检索条件 -->
    <lq-form :form="searchForm" ref="searchFormRef">
      <template #footer>
        <div>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="success" @click="handleSave"> 新增</el-button>
          <el-button type="danger" @click="handleBatchRemove">批量删除</el-button>
          <el-button type="warning" size="small" @click="handleExport">导出</el-button>
        </div>
      </template>

    </lq-form>

    <br>
    <!-- 数据列表 -->
    <div id="table">
      <lq-table ref="tableRef"
                :columns="columns"
                :records="tableData.records"
                size="default"
                :border="true"
                :header-cell-style="{background:'#e1eaf6', color:'#333333'}"
                :stripe="true"
                :pagination="paginationProps"
                @on-selections="handleSelectionChange"
                @on-pagination="handleCurrentChange"
      >
        <template #name="scope">
          <el-link type="primary" @click="handleView(scope.row.id)">{{ scope.row.name }}</el-link>
        </template>

        <template #operate="scope">
          <el-button @click="handleEdit(scope.row.id)" type="primary">编辑</el-button>
          <el-button @click="handleSingleRemove(scope.row.id)" type="danger">删除</el-button>
        </template>

      </lq-table>
    </div>


    <el-dialog v-model="dialog.visible"
               v-bind="{...dialog.innerAttrs}"
               v-on="dialog.events">
      <EntEmployeeForm ref="addProductsFormRef"  @flush="handleFlush"  />

    </el-dialog>


  </section>
</template>
<script setup lang="ts">
/**
 * --------------相关组件引入--------------------------
 */
import {ref, reactive, onMounted, nextTick} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

import EntEmployeeForm from "./ProductsForm.vue";
import LqForm from "@/components/LqForm.vue";
import LqTable from "@/components/LqTable.vue";
import axios from '@/api/index.js'

/**
 * ---------------状态变量定义-------------------------
 */
//获取表格组件实例
const tableRef = ref();

//获取新增或编辑窗口组件实例
const addProductsFormRef = ref();


const tableData = ref({
  records: [],
  pageSize: 10,
  tableSize: 'default',
  border: true,
});

//分页信息
const paginationProps = reactive({
  pageSize: tableData.value.pageSize,
  pageSizes: [5, 10, 20, 50, 100],
  total: 0,
  pageNum: 1,
  small: false,
  paginationAlign: 'right',
});


const searchForm = ref({
  innerAttrs: {
    labelPosition: 'right',
    labelWidth:  70,
  },
  model: {
    name: "",
    position: "",
    type: "",
    dept: "",
    mobilePhone: ""
  },
  //注意下面示例中select的写法，用的是下拉列表。
  //options存放对象数组，value是提交值，label是显示值。
  formItems: [
    {type: 'input', label: '产品名称: ', prop: 'proName', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '产品价格: ', prop: 'proPrice', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '产品图片: ', prop: 'proImg', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '生产日期: ', prop: 'proDate', span: 4, maxlength: 30, placeholder: ''},
    {type: 'select', label: '人员类型: ', prop: 'type', span: 4, options: [{label: '主要负责人', value: '主要负责人'},{label: '安全负责人', value: '安全负责人'},{label: '安全生产管理人员', value: '安全生产管理人员'},{label: '特殊作业人员', value: '特殊作业人员'},{label: '特种设备作业人员', value: '特种设备作业人员'},{label: '其他', value: '其他'}], },
  ],
  buttonsAttrs: {
    align: 'left'
  }
});


const columns = [
  {label: '', type: "selection", width: 40},
  {label: '序号', type: "index", width: 50},
  {label: "主键", prop: 'id', minWidth: 100},
   {label: "产品名称", prop: 'proName', minWidth: 100},
   {label: "产品价格", prop: 'proPrice', minWidth: 100},
   {label: "产品图片", prop: 'proImg', minWidth: 100},
   {label: "生产日期", prop: 'proDate', minWidth: 100},
   {label: '操作', prop: 'id', slotName: 'operate', slotted: true, align: 'center', fixed: 'right', minWidth: 150},
]


const dialog = ref({
  visible: false,
  innerAttrs: {
    id: 'ProductsFormDialog',
    class: 'ProductsFormDialog',
    title: '',
    width: "60%",
    top: '6vh'
  },
  events: {
    open: () => {
      console.log('dialog open.....');

    },
    close: () => {
      console.log('dialog close.....');

    },
  }
})
/**
 * --------------页面加载生命周期函数--------------------------
 */
onMounted(() => {
  queryData();
})

/**
 * --------------搜索查询功能--------------------------
 */
const handleQuery = () => {
  //每次查询都要从第一页开始
  resetPagination();
  queryData();
}

/**
 * --------------AJAX获取数据--------------------------
 */
const queryData = () => {
  let obj = Object.assign({}, searchForm.value.model, {pageNum: paginationProps.pageNum, pageSize: paginationProps.pageSize});
  axios.post('/products/getProductsPage', obj).then(({data}) => {
    if (data.code == '200') {
      tableData.value.records = data.data.list;
      paginationProps.total = data.data.total;
    }
  });
};

/**
 * --------------刷新-----------------
 */
const handleFlush = () => {
  dialog.value.visible = false;
  queryData();
}


/**
 * --------------分页操作-------------------
 */
const handleCurrentChange = () => {
  // 调用查询方法
  queryData();
};


const resetPagination = () => {
  paginationProps.pageNum = 1;
  paginationProps.pageSize = tableData.value.pageSize;
  paginationProps.total = 0;
};
/**
 * --------------编辑------------------
 */

const handleEdit = (id: string) => {
  dialog.value.visible = true;
  nextTick(()=>{
      addProductsFormRef.value.handleViewOrEdit(id, false)
  })
}

/**
 * --------------只读设置-------------------
 */
const handleView = (id: string) => {
  dialog.value.visible = true;
  nextTick(()=>{
    addProductsFormRef.value.handleViewOrEdit(id, true)
  })
}


/**
 * --------------新增--------------------------
 */

const handleSave = () => {
  //先清空表单，防止编辑污染
  dialog.value.visible = true;
  nextTick(()=>{
    addProductsFormRef.value.handleReset()
  })

}


/**
 * --------------删除操作--------------------------
 */
const handleSingleRemove = (id: string) => {
  ElMessageBox.confirm(`确认要删除吗!`, "确认信息", {
    type: "warning",
    distinguishCancelAndClose: true,
    confirmButtonText: "删除",
    cancelButtonText: "取消",
  })
      .then(() => {
        axios.delete('/products/deleteProductsById/'+id)
         .then(({data}) => {
          queryData();
          ElMessage({
            type: "success",
            message: "您已经成功删除了信息",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "您已经取消了删除操作",
        });
      });

}


/**
 * --------------多选删除操作--------------------------
 */


//选择的记录集
const selections = ref([]);
const handleSelectionChange = (items) => {
  selections.value = items.value.map((item) => item.id);
  // console.log('选择的ID:',...toValue(selections));
}


// 删除功能
const handleBatchRemove = () => {
  if (selections.value.length === 0) {
    ElMessage({
      type: "info",
      message: "请选择至少一个信息记录",
    });
  } else {
    ElMessageBox.confirm(`是否删除${selections.value.length}详细信息？删除后不可恢复!`, "确认信息", {
      type: "warning",
      distinguishCancelAndClose: true,
      confirmButtonText: "删除",
      cancelButtonText: "取消",
    })
        .then(() => {
          axios.delete('/products/deleteProductsById/'+selections.value.join(','))
          .then(({data}) => {
            queryData();
            ElMessage({
              type: "success",
              message: "您已经成功删除了信息",
            });
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "您已经取消了删除操作",
          });
        });
  }
};

</script>
